package com.boot.ys.mybatisplus.script;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Random;

/**
 * 文件夹下存在多个子文件夹，子文件夹里面有多个视频，多个视频截图视频存另外的文件夹,文件夹名称为那边的文件夹名称
 *
 * @author: 杨升
 * @date: 2024-08-17 15:47
 * @Version 1.0
 */


public class MoreVideImage {

    public static void main(String[] args) throws Exception {
        // 指定视频文件夹路径
        String rootFolder = "C:\\Users\\Acer\\Desktop\\测试\\视频";
        // 存放截图的根文件夹
        String outputRootFolder = "C:\\Users\\Acer\\Desktop\\测试\\输出\\";
        // 替换为你的ffmpeg可执行文件路径
        String ffmpegPath = "D:\\software\\FFmpeg\\ffmpeg-n5.0-latest-win64-lgpl-shared-5.0\\bin\\ffmpeg.exe";
        // 每个视频需要截取的图片张数
        Integer imageCount = 12;

        File rootDir = new File(rootFolder);
        File[] subDirs = rootDir.listFiles(File::isDirectory);

        if (subDirs != null) {
            for (File subDir : subDirs) {
                String subDirName = subDir.getName();
                String outputFolder = outputRootFolder + subDirName + "\\";
                File outputDir = new File(outputFolder);
                outputDir.mkdirs(); // 创建文件夹

                File[] videoFiles = subDir.listFiles(VideoImageAbo::isVideoFile);

                if (videoFiles != null) {
                    for (File videoFile : videoFiles) {
                        // 执行生成截图操作
                        image(videoFile.getAbsolutePath(), outputFolder, ffmpegPath, imageCount);
                    }
                }
            }
        }
    }

    public static void image(String videoFilePath, String outputFolder, String ffmpegPath, Integer imageCount) throws IOException {
        // 这里读取一下每个视频的时间长度
        double videoLongTime = getVideoLongTime(videoFilePath, ffmpegPath);

        double time = videoLongTime / imageCount;
        // 每隔多少秒取一次数据

        File videoFile = new File(videoFilePath);
        File outputDir = new File(outputFolder);
        if (!outputDir.exists()) {
            outputDir.mkdirs(); // 创建存放截图的文件夹
        }
        try {
            Random random = new Random();
            int randomNumber = random.nextInt(10000); // 生成 0 到 9999 之间的随机数字
// 构建 ffmpeg 命令
            String ffmpegCommand = ffmpegPath + " -i \"" + videoFile.getAbsolutePath() + "\" -vf fps=1/" + time + " \"" + outputFolder + randomNumber + "%d.jpg\"";
            System.out.println("执行命令: " + ffmpegCommand);
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", ffmpegCommand);
            pb.redirectErrorStream(true);

            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(new String(line.getBytes(), Charset.defaultCharset()));
                }
            }
            int errCode = process.waitFor();
            if (errCode == 0) {
                System.out.println("截图完成。");
            } else {
                System.err.println("截图失败。ffmpeg 命令返回错误码: " + errCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.out.println("发生错误: " + e.getMessage());
        }
    }

    public static boolean isVideoFile(File file) {
        String fileName = file.getName().toLowerCase();
        return fileName.endsWith(".mp4") || fileName.endsWith(".avi") || fileName.endsWith(".mov") || fileName.endsWith(".mkv");
        // 根据需要添加更多视频格式
    }

    public static double getVideoLongTime(String videoFilePath, String ffmpegPath) throws IOException {
        String duration = "";

        // 构建 FFmpeg 命令
        String[] cmd = {ffmpegPath, "-i", videoFilePath};

        // 执行命令
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        Process process = processBuilder.start();

        // 读取 FFmpeg 的输出信息
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 查找包含 Duration 字段的行
                if (line.contains("Duration:")) {
                    int start = line.indexOf("Duration:") + "Duration:".length();
                    int end = line.indexOf(",", start);
                    duration = line.substring(start, end).trim();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 等待进程结束
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // duration 的格式通常为 "hh:mm:ss.xxx"
        String[] timeComponents = duration.split(":");
        int hours = Integer.parseInt(timeComponents[0].trim());
        int minutes = Integer.parseInt(timeComponents[1].trim());
        double seconds = Double.parseDouble(timeComponents[2].trim());

        // 计算总秒数
        double totalSeconds = hours * 3600 + minutes * 60 + seconds;

        return totalSeconds;
    }
}
